package com.bianmaba.jobs.collection.dispatcher;

import com.bianmaba.beans.datacollection.CollectionTask;
import com.bianmaba.beans.datacollection.ExecuteLog;
import com.bianmaba.dc.bean.CollectionRequest;
import com.bianmaba.dc.bean.CollectorResponse;
import com.bianmaba.dc.bean.JobParameter;
import com.bianmaba.dc.bean.TaskStatus;
import com.bianmaba.remote.supports.CollectorRemoteRequestService;
import com.bianmaba.services.datacollection.ExecuteLogRecorder;
import com.bianmaba.services.datacollection.ICollectionTaskService;
import com.bianmaba.services.datacollection.ITaskInstanceService;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

@Log4j2
public abstract class AbstractDispatcher implements Job {
    @Autowired
    protected CollectorRemoteRequestService remoteRequestService;
    @Autowired
    protected ExecutorService executorService;
    @Autowired
    protected ICollectionTaskService collectionTaskService;
    @Autowired
    protected ITaskInstanceService taskInstanceService;
    @Autowired
    protected ExecuteLogRecorder logWriter;

    protected CollectionTask task;
    protected JobExecutionContext context;

    @Override
    public void execute(JobExecutionContext context) {
        this.context = context;
        JobDataMap jobDataMap = this.context.getMergedJobDataMap();
        String taskInstanceId = context.getMergedJobDataMap().getString(JobParameter.TASK_INSTANCE_ID.getName());

        haldlerInitMessages(taskInstanceId, (List<String>) jobDataMap.get("messages"));

        //判断初始化是否成功，如果不成功则退出任务
        if (jobDataMap.containsKey("inited") && jobDataMap.getBoolean("inited")) {
            String taskId = jobDataMap.getString(JobParameter.TASK_ID.getName());
            this.task = collectionTaskService.findOne(taskId);
            //准备发起采集请求
            boolean success = sendCollectionRequest(taskInstanceId);
            if (success) {
                logWriter.put(ExecuteLog.of(taskInstanceId, "采集请求已经提交采集器，开始监听状态。"));
            }
        } else {
            taskInstanceService.updateStatus(taskInstanceId, TaskStatus.UNSUCCESSFUL.getIndex());
        }
    }

    //处理初始化过程中产生的日志
    protected void haldlerInitMessages(String taskInstanceId, List<String> messages) {
        List<String> msgs = new ArrayList<>(0);
        if (messages != null) {
            msgs.addAll(messages);
            for (String item : msgs) {
                logWriter.put(ExecuteLog.of(taskInstanceId, item));
            }
            messages.removeAll(msgs);
        }
    }


    protected boolean sendCollectionRequest(String taskInstanceId) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        JobDataMap jobDatas = context.getMergedJobDataMap();
        //创建采集参数
        CollectionRequest collectionRequest = new CollectionRequest(jobDatas.getWrappedMap());

        HttpEntity<CollectionRequest> entity = new HttpEntity(collectionRequest, headers);

        String url = this.task.getCollectionInterface().getBaseUrl() + "collect";

        logWriter.put(ExecuteLog.of(taskInstanceId, "准备发起采集请求：" + url));

        CollectorResponse<Boolean> result = (CollectorResponse<Boolean>) remoteRequestService.post(url, entity);
        if (!result.isSuccess() || !result.getData()) {
            logWriter.put(ExecuteLog.of(taskInstanceId, "采集请求异常！"));
            logWriter.put(ExecuteLog.of(taskInstanceId, result.getResult()));
            taskInstanceService.updateStatus(taskInstanceId, TaskStatus.EXCEPTIONAL.getIndex());
            return false;
        } else {
            logWriter.put(ExecuteLog.of(taskInstanceId, result.getResult()));
            return true;
        }
    }
}
